/*
 * DailyMission.cpp
 *
 *  Created on: 2014. 4. 9.
 *      Author: mega
 */

#include "../User.h"
#include "../NResource/Static.h"
#include "DailyMission.h"

namespace ProjectZ { namespace NLogic {

DailyMission::DailyMission(User * pUser)
{
	_pUser = pUser;
	_clsVector.reserve(static_cast<int>(MissionType::__MAX__));

	for (int i = static_cast<int>(MissionType::SPECIAL_MISSION); i < static_cast<int>(MissionType::__MAX__); i++)
	{
		DailyMission::Data * pData = new DailyMission::Data;
		pData->missionType = i;

		_clsVector[i] = pData;
	}
}

DailyMission::~DailyMission()
{
	std::for_each(_clsVector.begin(), _clsVector.end(), [&](DailyMission::Data * pData) {
		delete pData;
	});
}

void
DailyMission::Initialize()
{
	for (int i = static_cast<int>(MissionType::SPECIAL_MISSION); i < static_cast<int>(MissionType::__MAX__); i++)
	{
		_clsVector[i]->Clear();
		_clsVector[i]->missionType = i;
	}
}

void
DailyMission::Finalize()
{
}

DailyMission::Data *
DailyMission::GetData(MissionType eType)
{
	return _clsVector[static_cast<int>(eType)];
}

void
DailyMission::MissionComplete(MissionType eType)
{
	if (false == NResource::Static::Instance().GetContentsOpenResource()->IsOpen(static_cast<int>(ContentsOpen::DAILY_MISSION)))
	{
		DEBUGLOG("%s : Contents is Not Open", __FUNCTION__);
		return;
	}

	this->CheckMissionInitialize();

	int nType = static_cast<int>(eType);

	NResource::DailyMissionResource::Flyweight * pFly = NResource::Static::Instance().GetDailyMissionResource()->GetFly(nType);
	if (NULL == pFly)
	{
		return;
	}

	if (_clsVector[nType]->completeCount < pFly->_COMPLETE_COUNT)
	{
		_clsVector[nType]->completeCount++;
	}

	// 미션을 완료하고, 보상을 받지 않은 경우 완료 패킷 전송
	if (_clsVector[nType]->completeCount >= pFly->_COMPLETE_COUNT && 2 != _clsVector[nType]->isReward)
	{
		_clsVector[nType]->isReward = 1;

		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		pAck->MakePacket(CMD_SC_COMPLETE_DAILY_MISSION);
		_pUser->Send(pAck);
	}

	// 모든 일일 미션을 완료하였는지 판단하여
	// 스페셜 보상 수령 가능 상태로 변경
	if (true == this->IsAllMissionComplete())
	{
		_clsVector[static_cast<int>(MissionType::SPECIAL_MISSION)]->isReward = 1;
	}

	_pUser->FlushCharacterInfoCache();
}

bool
DailyMission::IsAllMissionComplete()
{
	// 이미 보상을 받은 경우
	if (2 == _clsVector[static_cast<int>(MissionType::SPECIAL_MISSION)]->isReward)
		return false;

	for (int i = static_cast<int>(MissionType::MISSION1); i < static_cast<int>(MissionType::__MAX__); i++)
	{
		if (0 == _clsVector[i]->isReward)
			return false;
	}

	return true;
}

void
DailyMission::CheckMissionInitialize()
{
	time_t initTime = NLogic::NFunction::GetDailyMissionInitTime();

	// 초기화
	if (initTime >= static_cast<time_t>(_pUser->GetCharacterInfo().reserve1))
	{
		this->Initialize();
		_pUser->FlushCharacterInfoCache();
	}

	_pUser->GetCharacterInfo().reserve1 = time(NULL);
}

} /* namespace NLogic */ } /* namespace ProjectZ */
